package UF_MAIL;

public class Example_02 {
    public Collection<Message> getMessages(final Session session,
                                           final String... folderNames) throws MessagingException {
        final Collection<Message> result = new ArrayList<Message>();
        Store store = session.getStore("pop3");
        store.connect();

        for (String folderName : folderNames) {
            Folder folder = getFolder(store, folderName);
            if (folder != null) {
                Message messages[] = folder.getMessages();
                for (int i = 0, n = messages.length; i < n; i++) {
                    result.add(messages[i]);
                }
            }
        }

        return result;
    }

    private Folder getFolder(Store store, final String folderName) throws MessagingException {
        if (folderName == null) {
            return null;
        }

        try {
            Folder folder = store.getFolder(folderName);
            folder.open(Folder.READ_ONLY);
            return folder;
        } catch (MessagingException e) {
            store.close();
            throw e;
        }
    }
}
